/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.pad;

import javax.inject.Inject;

import ru.irenproject.Action;
import ru.irenproject.Check;
import ru.irenproject.Utils;
import ru.irenproject.Visual;
import ru.irenproject.pad.PadProtos.BlockType;
import ru.irenproject.pad.PadProtos.ImageFormat;
import ru.irenproject.pad.PadProtos.PadEditorShape;
import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.AspectId;
import ru.irenproject.store.Event;
import ru.irenproject.store.Initializer;
import ru.irenproject.store.Stash;
import ru.irenproject.store.Thing;

import com.google.protobuf.ByteString;
import com.google.protobuf.Message;

public final class PadEditor extends AbstractThing implements Visual {
  public static final class InsertFragmentInput {
    public int position;
    public InsertFragmentBlockInput[] blocks;
  }

  public static final class InsertFragmentBlockInput {
    public BlockType type;
    public String text;
    public ImageFormat imageFormat;
    public byte[] imageData;
    public String sourceFormat;
    public byte[] sourceData;
  }

  public static final class DeleteFragmentInput {
    public int position;
    public int length;
  }

  private static final AspectId ASPECT_ID = new AspectId(0xa64bc7ac7f128664L);

  public static PadEditor open(final Pad pad) {
    return Utils.requireAspect(pad, ASPECT_ID, PadEditor.class, new Initializer<PadEditor>() {
      @Override public void initialize(PadEditor target) {
        target.prepare(pad);
      }
    });
  }

  public static PadEditor create(Pad pad) {
    PadEditor res = pad.store().create(PadEditor.class);
    res.prepare(pad);
    return res;
  }

  @Stash private PadProtos.PadEditor.Builder $;

  @Inject PadEditor() {}

  private void prepare(Pad pad) {
    $.setPad(pad.id());
    pad.addListener(this);
  }

  public Pad pad() {
    return get($.getPad(), Pad.class);
  }

  @Override protected void handleEvent(Event e, Thing source) {
    if (e instanceof Pad.ChangeEvent) {
      markForRender();
    }
  }

  @Override public Message render() {
    return PadEditorShape.newBuilder()
        .addAllBlock(pad().blockList())
        .build();
  }

  @Action public void doInsertFragment(InsertFragmentInput in) {
    Check.inputNotNull(in.blocks);

    int p = in.position;
    for (InsertFragmentBlockInput b : in.blocks) {
      Check.inputNotNull(b);
      Check.inputNotNull(b.type);
      switch (b.type) {
        case TEXT: {
          pad().insertText(Check.inputNotNull(b.text), p);
          p += b.text.length();
          break;
        }
        case IMAGE: {
          ImageSource source = (b.sourceFormat == null) ? null
              : ImageSource.create(
                  b.sourceFormat,
                  ByteString.copyFrom(Check.inputNotNull(b.sourceData)));
          pad().insertImage(Check.inputNotNull(b.imageFormat),
              Check.inputNotNull(b.imageData), source, p);
          ++p;
          break;
        }
        case LINE_FEED: {
          pad().insertLineFeed(p);
          ++p;
          break;
        }
      }
    }
  }

  @Action public void doDeleteFragment(DeleteFragmentInput in) {
    pad().deleteFragment(in.position, in.length);
  }
}
